var cheerio = require('cheerio');
var fs = require('fs');
var lib = require('../../lib/index.js');
var config = require('./detailConfig.json');

// 1.创建数据链接
var connection = lib.connection();
connection.on('error', function(err) {
    console.log('db error', err);
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        connection = lib.connection();
    } else {
        throw err;
    }
});

// 监听父进程消息
process.on('message', (msg) => {
  console.log(msg);
});

// lib.eventListener.on('do_spider', function(data) {
//     queryList();
// });
// lib.eventEmitter.emit('do_spider','init');
queryList();

function endProgram() {
    console.log('中止程序,准备重启');

    fs.writeFile('./detailConfig.json', JSON.stringify(config), function(err) {
        if (err) {
            console.log(err);
        }else{
            console.log('中止程序前配置文件保存成功');
            process.exit(0);//主动中止程序
        }
    });
}

async function queryList() {
    // 延迟执行往后的程序
    await lib.wait(500);

    var sql = "select companyName,productsUrl from 1688_supplys"+config.tableIndex+" limit "+config.queryParam.start+",1;";
    connection.query(sql,async function(err, result) {
        if (err) {
            console.log(err);
            return;
        }
        var data = result[0];
        if(!data){
            console.log('1688_supplys'+config.tableIndex+'表采集结束,5s后采集下一张表');
            console.log('-----------end-----------');
            console.log();
            console.log();
            console.log();
            config.queryParam.start = 0;
            config.tableIndex++;

            await lib.wait(5000);

            queryList();
            return false;
        }

        lib.credit1688ProductTable(connection,'1688_supplys'+config.tableIndex+'_products');

        console.log('-----------'+ lib.getTime() +'-----------');
        console.log('1688_supplys'+config.tableIndex+',第'+config.queryParam.start+'条记录采集中...');
        console.log('查询企业:'+data.companyName);
        // 根据企业名查询
        let result1 = await lib.myRequest('https://www.alibaba.com/trade/search?fsb=y&IndexArea=company_en&CatId=&SearchText='+data.companyName).catch((e)=>{
            console.log('查询企业非英文 跳过');
            console.log(e);
            config.queryParam.start++;
            return false;
        });
        if(!result1){
            endProgram();
            return false;
        }
        var $ = cheerio.load(result1);
        var title = $('.m-item').eq(0).find('.title').text().trim();
        var url = $('.m-item').eq(0).find('.title a').attr('href');
        // console.log(title);
        // console.log(data.companyName);
        if(title != data.companyName){
            console.log('当前查询的展商名称与数据库不一致,跳过');
            console.log();
            console.log();

            config.queryParam.start++;
            queryList();
            return false;
        }
        // console.log(url);
        // .fm.alibaba.com/
        var start_pos = url.indexOf('member/');
        // console.log(start_pos);
        if(start_pos>-1){//重定向的url
            var end_pos = url.indexOf('company_profile')-1;
            url = 'https://' + url.substring(start_pos+7,end_pos) + '.fm.alibaba.com';
        }else{
            var end_pos = url.indexOf('company_profile')-1;
            url = url.substring(0,end_pos);
            // console.log(url);
        }
        // console.log(url);
        // return false;

        var products = data.productsUrl.split(',');
        var promiseArr = [];
        for(var i=0;i<products.length;i++){
            var item = products[i];
            item = url + products[i];

            // console.log(item);
            // return false;

            var promiseFun = new Promise((resolve, reject) => {
                getDetail({
                    companyName:data.companyName,
                    url:item,
                    index:i
                },resolve, reject);
            });
            promiseArr.push(promiseFun);
        }

        // return false;

        Promise.all(promiseArr).then((values) => {
            for(var i=0;i<values.length;i++){
                var item = values[i];
                // console.log('产品'+i+',返回状态:'+item.code);
                console.log(item.code);
                if(item.code == 200){
                    // 插入数据
                    lib.insertData(connection,'1688_supplys'+config.tableIndex+'_products',item.data);
                }
            }

            // return false;
            console.log();
            console.log();
            // 下一企业产品
            config.queryParam.start++;
            queryList();
        }).catch((e)=>{
            console.log('promise.all Err');
            // console.log(e);
        });
    });
}

// 产品内容
async function getDetail(detailItem,resolve,reject) {
    console.log('产品链接'+detailItem.index+':'+detailItem.url);
    let result = await lib.myRequest(detailItem.url).catch((e)=>{
        console.log(e);
        return false;
    });
    if(!result){
        endProgram();
        return false;
    }
    let $ = cheerio.load(result);

    // 所在目录
    var fullCategory = [];
    $('.detail-breadcrumb .breadcrumb-item').each(function () {
        fullCategory.push($(this).find('a').text().trim());
    });
    let imgs = [];
    let videoSrc = $('#video-preload').attr('src');
    let videoImg = '';
    $('.widget-detail-booth-image .inav li').each(function (index) {
        if($(this).hasClass('play')){
            videoImg = $(this).find('img').attr('src');
        }else{
            let src = $(this).find('img').attr('src').replace('.png_50x50','').replace('.jpg_50x50','').replace('.gif_50x50','');
            imgs.push(src);
        }
    });

    let title = $('.ma-title').text();
    let minOrder = $('.ma-min-order').text();
    let payments = $('.assurance-payment .payment-val').text();

    var overview = {};
    $('.do-entry-list dl.do-entry-item').each(function () {
        let key = $(this).find('dt').text().replace(':','').trim();
        let value = '';
        if(key === 'Lead Time'){
            value = $(this).find('.do-entry-item-val').html();
            // .replace(/[\n\r]/g,'<br>').trim()
        }else{
            value = $(this).find('.do-entry-item-val').text().trim();
        }

        overview[key] = value;
    });
    let richText = $('#J-rich-text-description').html();

    var insert_data = {
        title:title,
        supply:detailItem.companyName,
        fullCategory:fullCategory.toString(),
        imgs:imgs.toString(),
        videoSrc:videoSrc||'',
        videoImg:videoImg||'',
        minOrder:minOrder,
        payments:payments,
        overview:JSON.stringify(overview),
        richText:richText,
        url:detailItem.url
    };
    // console.log(title);
    // console.log();
    // fs.writeFile('./detail.json', JSON.stringify(insert_data), function(err) {
    //     if (err) console.log(err);
    //     else console.log('写文件操作成功');
    // });
    resolve({
        code:200,
        data:insert_data
    })
}
